package com.miyake.dsp.osa;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class OsaCsv {
	double[] x = null;
	double[] level = null;
	OsaSetting setting = new OsaSetting();
	
	public OsaCsv(String filename) {
		readCSV(filename);
	}
	
	
	public double[] getX() {
		return x;
	}


	public void setX(double[] x) {
		this.x = x;
	}


	public double[] getLevel() {
		return level;
	}


	public void setLevel(double[] level) {
		this.level = level;
	}


	public OsaSetting getSetting() {
		return setting;
	}


	public void setSetting(OsaSetting setting) {
		this.setting = setting;
	}


	public void readCSV(String file) {

		try {
			BufferedReader reader = new BufferedReader(new FileReader(new File(file)));
			String line ="";
			boolean header = true;

			int index = 0;
			
			double start = 0, stop = 0;
			while( (line = reader.readLine()) != null) {
				String[] tmp = line.split(",");
				
				if (!header) {
					if (tmp.length < 2) {
						break;
					}
					level[index] = Double.valueOf(tmp[1]) * 1e-3;
					//level[index] = Math.log10(level[index]);
					index++;
				}
				
				if ( (tmp.length > 0)) {
					if (tmp[0].equals("Stop")) {
						header = false;
						stop = Double.valueOf(tmp[1]);
						double step = (stop - start) / (double)(x.length - 1);
						for (int i = 0; i < x.length; i++) {
							x[i] = start + (double)i * step;
						}
						setting.setStopWavelength(stop);
					}
					else if (tmp[0].equals("Start")) {
						start = Double.valueOf(tmp[1]);
						setting.setStartWavelength(start);
					}
					else if (tmp[0].equals("Sampling Points")) {
						level = new double[Integer.valueOf(tmp[1])];
						if (x == null) {
							x = new double[Integer.valueOf(tmp[1])];
						}
						setting.setSamplingPoints(x.length);
					}
					else if (tmp[0].equals("Actual Resolution")) {
						setting.setActualResolution(Double.valueOf(tmp[1]));
					}
					else if (tmp[0].equals("Resolution")) {
						setting.setSettingResolution(Double.valueOf(tmp[1]));
					}		
					else if (tmp[0].equals("Value In Air/Vacuum")) {
						if (tmp[1].equals("Air")) {
							setting.setAir(true);
						}
						else {
							setting.setAir(false);
						}
					}
				}
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			LogTrace.writeLog(e.toString());
		} catch (IOException e) {
			e.printStackTrace();
			LogTrace.writeLog(e.toString());
		}
	}
}
